import sys
import time
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp, hooks
from modbus_tk.modbus import Slave

def main():
    """创建Modbus TCP从站模拟器"""
    try:
        # 创建服务器
        server = modbus_tcp.TcpServer(port=5022)
        
        # 日志钩子，用于打印通信信息
        # def on_after_recv(server, master, bytes_data):
        #     print(f"收到主站请求: {bytes_data.hex()}")

        # def on_before_send(server, master, bytes_data):
        #     print(f"发送给主站响应: {bytes_data.hex()}")

        # hooks.install_hook("modbus_tcp.TcpServer.after_recv", on_after_recv)
        # hooks.install_hook("modbus_tcp.TcpServer.before_send", on_before_send)

        # 启动服务器
        server.start()
        print("Modbus从站模拟器启动成功，端口: 502")

        # 创建一个从站，地址为1
        slave_1 :Slave = server.add_slave(1)
        
        # 为从站添加数据块
        # 线圈 (Coils): 地址范围 0-99，初始值都为False
        slave_1.add_block('0', cst.COILS, 0, 100)
        
        # # 离散输入 (Discrete Inputs): 地址范围 0-99，初始值都为False
        # slave_1.add_block('1', cst.DISCRETE_INPUTS, 0, 100)
        
        # # 保持寄存器 (Holding Registers): 地址范围 0-99，初始值为0-99
        # slave_1.add_block('2', cst.HOLDING_REGISTERS, 0, 100, values=[i for i in range(100)])
        
        # # 输入寄存器 (Input Registers): 地址范围 0-99，初始值为100-199
        # slave_1.add_block('3', cst.INPUT_REGISTERS, 0, 100, values=[i+100 for i in range(100)])

        # 设置地址0的线圈为True
        slave_1.set_values('0', 0, True)
        print("已设置线圈地址0的初始状态为: True")

        print("从站1配置完成，包含以下数据块:")
        print("- 线圈 (Coils): 0-99")
        print("- 离散输入 (Discrete Inputs): 0-99")
        print("- 保持寄存器 (Holding Registers): 0-99 (初始值 0-99)")
        print("- 输入寄存器 (Input Registers): 0-99 (初始值 100-199)")
        
        # 让服务器持续运行
        while True:
            # 每5秒翻转第一个线圈的状态
            time.sleep(1)
            # current_value = slave_1.get_values('0', 0, 1)[0]
            # slave_1.set_values('0', 0, not current_value)
            # print(f"自动翻转线圈0的状态为: {not current_value}")
            
    except modbus_tk.modbus.ModbusError as e:
        print(f"Modbus错误: {e}")
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        # 停止服务器
        if 'server' in locals():
            server.stop()
        print("Modbus从站模拟器已停止")

if __name__ == "__main__":
    main()
